package com.ruoyi.filemanager.command;

import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.filemanager.constant.ElFinderConstants;
import com.ruoyi.filemanager.service.ElfinderStorage;
import com.ruoyi.filemanager.service.VolumeHandler;
import com.ruoyi.filemanager.util.ImageUtil;

public class GetCommand extends AbstractJsonCommand implements ElfinderCommand
{
    public static final String ENCODING = Constants.UTF8;
    public static final String IMAGE_MIME_TYPE = "image";

    @Override
    protected void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, JSONObject json)
            throws Exception
    {
        final String target = request.getParameter(ElFinderConstants.ELFINDER_PARAMETER_TARGET);
        final VolumeHandler vh = findTarget(elfinderStorage, target);
        final InputStream is = vh.openInputStream();
        if (vh.getMimeType().contains(IMAGE_MIME_TYPE))
        {
            json.put(ElFinderConstants.ELFINDER_PARAMETER_CONTENT, ImageUtil.imgToBase64(is, vh.getMimeType()));
        }
        else
        {
            final String content = IOUtils.toString(is, ENCODING);
            is.close();
            json.put(ElFinderConstants.ELFINDER_PARAMETER_CONTENT, content);
        }
    }
}
